<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>SQL测试数据生成器</title>
    <link rel="stylesheet" href="./libs/element-plus.css">
    <script src="./libs/vue.global.js"></script>
    <script src="./libs/element-plus.js"></script>
    <script src="./libs/element-plus-icons-vue.js"></script>
    <script src="./libs/faker.min.js"></script>
    <script src="./libs/ai-service.js"></script>
    <script src="./libs/db-service.js"></script>
    <style>
        .table-config {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
        }
        .column-list {
            margin-top: 20px;
        }
        .column-item {
            background-color: #f5f7fa;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
        }
        .sql-result {
            position: relative;
        }
        .copy-btn {
            position: absolute;
            right: 10px;
            top: 10px;
            z-index: 1;
        }
        /* 添加全屏加载遮罩样式 */
        .full-screen-loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-text {
            color: white;
            margin-top: 20px;
            font-size: 16px;
        }
        /* 禁用状态样式 */
        .disabled-container {
            pointer-events: none;
            opacity: 0.7;
        }
        .settings-btn {
            position: fixed;
            right: 20px;
            top: 20px;
            z-index: 1000;
        }
        .api-key-input {
            width: 300px;
        }
        /* 历史记录抽屉样式 */
        .history-drawer .el-drawer__body {
            padding: 0;
        }
        .history-item {
            padding: 15px;
            border-bottom: 1px solid #ebeef5;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .history-item:hover {
            background-color: #f5f7fa;
        }
        .history-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .history-item-title {
            font-weight: bold;
        }
        .history-item-time {
            color: #909399;
            font-size: 12px;
        }
        .history-item-content {
            color: #606266;
            font-size: 14px;
            margin: 5px 0;
        }
        .history-empty {
            text-align: center;
            padding: 20px;
            color: #909399;
        }
        .history-search {
            padding: 15px;
            border-bottom: 1px solid #ebeef5;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 配置按钮 -->
        <el-button 
            class="settings-btn" 
            type="primary" 
            circle 
            @click="showSettings = true"
            :icon="Setting"
        ></el-button>

        <!-- 配置对话框 -->
        <el-dialog
            v-model="showSettings"
            title="配置中心"
            width="500px"
        >
            <el-form label-width="120px">
                <el-form-item label="API Key">
                    <el-input
                        v-model="settings.apiKey"
                        class="api-key-input"
                        placeholder="请输入API Key"
                        show-password
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-alert
                        title="API Key说明"
                        type="info"
                        description="API Key用于访问AI服务，请妥善保管。如果没有API Key，请前往智谱AI官网申请：https://open.bigmodel.cn/"
                        :closable="false"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showSettings = false">取消</el-button>
                    <el-button type="primary" @click="saveSettings">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 主界面内容 -->
        <el-container style="padding: 20px;">
            <!-- 全屏加载动画 -->
            <div v-if="loading" class="full-screen-loading">
                <el-icon class="is-loading" :size="50" color="white"><Loading /></el-icon>
                <div class="loading-text">{{ loadingText }}</div>
                <el-button type="danger" @click="cancelOperation" style="margin-top: 20px;">取消操作</el-button>
            </div>

            <el-main :class="{ 'disabled-container': loading }">
                <h2>SQL测试数据生成器</h2>
                
                <!-- 配置区域 -->
                <div class="table-config">
                    <!-- Tab切换 -->
                    <el-tabs v-model="activeTab" :disabled="parseConfig.loading">
                        <el-tab-pane label="手动配置" name="manual">
                            <el-form label-width="100px">
                                <el-form-item label="表名">
                                    <el-input 
                                        v-model="tableConfig.tableName" 
                                        placeholder="请输入表名"
                                        :disabled="parseConfig.loading"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button 
                                        type="primary" 
                                        @click="addColumn"
                                        :disabled="parseConfig.loading"
                                    >
                                        <el-icon><plus /></el-icon> 添加字段
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        
                        <el-tab-pane label="解析建表语句" name="parse">
                            <el-form label-width="100px">
                                <el-form-item label="CREATE TABLE">
                                    <el-input
                                        v-model="createTableSQL"
                                        type="textarea"
                                        :rows="5"
                                        placeholder="请输入CREATE TABLE语句"
                                        :disabled="parseConfig.loading"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-radio-group 
                                        v-model="parseConfig.useAI" 
                                        style="margin-right: 20px;"
                                        :disabled="parseConfig.loading"
                                    >
                                        <el-radio :label="true">
                                            <el-tooltip content="使用AI分析字段，推荐更合适的数据类型">
                                                <span>AI智能解析 <el-tag size="small" type="success" v-if="parseConfig.lastAnalysis">已解析</el-tag></span>
                                            </el-tooltip>
                                        </el-radio>
                                        <el-radio :label="false">普通解析</el-radio>
                                    </el-radio-group>
                                    <el-button 
                                        type="primary" 
                                        :loading="parseConfig.loading"
                                        :disabled="parseConfig.loading"
                                        @click="parseCreateTable"
                                    >
                                        <el-icon><document /></el-icon> 解析
                                    </el-button>
                                </el-form-item>
                                <el-form-item v-if="parseConfig.lastAnalysis">
                                    <el-alert
                                        title="AI解析结果"
                                        type="success"
                                        :description="parseConfig.lastAnalysis"
                                        show-icon
                                    />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>

                        <el-tab-pane label="历史记录" name="history">
                            <!-- 搜索框 -->
                            <div class="history-search" style="padding: 0 0 15px 0;">
                                <el-input
                                    v-model="historySearch"
                                    placeholder="搜索表名"
                                    clearable
                                    @input="searchHistory"
                                >
                                    <template #prefix>
                                        <el-icon><search /></el-icon>
                                    </template>
                                </el-input>
                            </div>

                            <!-- 历史记录列表 -->
                            <div v-if="historyRecords.length > 0">
                                <div 
                                    v-for="record in historyRecords" 
                                    :key="record.id" 
                                    class="history-item"
                                    style="background-color: var(--el-fill-color-light);"
                                >
                                    <div class="history-item-header">
                                        <span class="history-item-title">{{ record.tableName }}</span>
                                        <div>
                                            <el-button 
                                                type="primary" 
                                                link 
                                                @click="loadHistory(record)"
                                            >加载</el-button>
                                            <el-button 
                                                type="danger" 
                                                link 
                                                @click="deleteHistory(record.id)"
                                            >删除</el-button>
                                        </div>
                                    </div>
                                    <div class="history-item-time">
                                        {{ new Date(record.timestamp).toLocaleString() }}
                                    </div>
                                    <div class="history-item-content">
                                        字段数：{{ record.columns.length }}
                                        <el-tag size="small" style="margin-left: 10px;">
                                            {{ record.useAI ? 'AI模式' : '普通模式' }}
                                        </el-tag>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="history-empty">
                                <el-empty description="暂无历史记录"></el-empty>
                            </div>

                            <!-- 底部操作栏 -->
                            <div style="margin-top: 15px; text-align: right;">
                                <el-button 
                                    type="danger" 
                                    @click="clearHistory"
                                    :disabled="historyRecords.length === 0"
                                >清空历史</el-button>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>

                <!-- 字段列表 -->
                <div v-if="tableConfig.columns.length > 0" class="column-list">
                    <el-card>
                        <template #header>
                            <div class="card-header">
                                <span>表结构：{{ tableConfig.tableName }}</span>
                            </div>
                        </template>
                        
                        <el-table :data="tableConfig.columns" border stripe>
                            <el-table-column label="字段名" width="180">
                                <template #default="scope">
                                    <el-input 
                                        v-model="scope.row.name" 
                                        placeholder="字段名"
                                        :disabled="parseConfig.loading"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="字段类型" width="180">
                                <template #default="scope">
                                    <el-select 
                                        v-model="scope.row.type" 
                                        placeholder="字段类型" 
                                        style="width: 100%"
                                        :disabled="parseConfig.loading"
                                    >
                                        <el-option-group
                                            v-for="group in [
                                                {label: '字符串', types: ['VARCHAR(255)', 'CHAR(50)', 'TEXT']},
                                                {label: '数值', types: ['INT', 'BIGINT', 'DECIMAL(10,2)', 'FLOAT']},
                                                {label: '日期时间', types: ['DATETIME', 'DATE', 'TIMESTAMP']},
                                                {label: '其他', types: ['BOOLEAN', 'JSON']}
                                            ]"
                                            :key="group.label"
                                            :label="group.label"
                                        >
                                            <el-option
                                                v-for="type in group.types"
                                                :key="type"
                                                :label="type"
                                                :value="type"
                                            ></el-option>
                                        </el-option-group>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="数据类型">
                                <template #default="scope">
                                    <div style="display: flex; align-items: center;">
                                        <!-- AI模式下显示文本框 -->
                                        <template v-if="parseConfig.useAI">
                                            <el-input 
                                                v-model="scope.row.dataType"
                                                placeholder="AI推荐的数据类型"
                                                :readonly="true"
                                                :disabled="parseConfig.loading"
                                            ></el-input>
                                        </template>
                                        <!-- 普通模式下显示下拉框 -->
                                        <template v-else>
                                            <el-select 
                                                v-model="scope.row.dataType" 
                                                placeholder="数据类型" 
                                                style="width: 100%"
                                                :disabled="parseConfig.loading"
                                            >
                                                <el-option
                                                    v-for="option in dataTypeOptions"
                                                    :key="option.value"
                                                    :label="option.label"
                                                    :value="option.value">
                                                </el-option>
                                            </el-select>
                                        </template>
                                        <el-tag 
                                            v-if="scope.row.aiRecommended" 
                                            size="small" 
                                            type="success"
                                            style="margin-left: 5px;"
                                        >
                                            AI推荐
                                        </el-tag>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button 
                                        type="danger" 
                                        @click="removeColumn(scope.$index)" 
                                        size="small"
                                        :disabled="parseConfig.loading"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div style="margin-top: 20px;">
                            <el-form inline>
                                <el-form-item label="生成数量">
                                    <el-input-number 
                                        v-model="generateConfig.count" 
                                        :min="1" 
                                        :max="1000"
                                        :disabled="parseConfig.loading"
                                    ></el-input-number>
                                </el-form-item>
                                <el-form-item>
                                    <el-button 
                                        type="primary" 
                                        @click="generateData"
                                        :disabled="parseConfig.loading"
                                    >
                                        <el-icon><magic-stick /></el-icon> 生成SQL
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-card>
                </div>
                
                <!-- 生成结果 -->
                <div v-if="generatedSQL" class="sql-result" style="margin-top: 20px;">
                    <el-card>
                        <template #header>
                            <div class="card-header">
                                <span>生成结果</span>
                                <el-button 
                                    class="copy-btn" 
                                    type="primary" 
                                    link 
                                    @click="copySQL"
                                    :disabled="parseConfig.loading"
                                >
                                    <el-icon><document-copy /></el-icon> 复制
                                </el-button>
                            </div>
                        </template>
                        <el-input
                            v-model="generatedSQL"
                            type="textarea"
                            :rows="10"
                            readonly
                            :disabled="parseConfig.loading"
                        ></el-input>
                    </el-card>
                </div>
            </el-main>
        </el-container>
    </div>

    <script>
        const { createApp, ref } = Vue
        const { Setting } = ElementPlusIconsVue
        const faker = window.faker.faker

        const app = {
            data() {
                return {
                    // 表结构配置
                    tableConfig: {
                        tableName: '',
                        columns: []
                    },
                    // 生成配置
                    generateConfig: {
                        count: 10
                    },
                    // 数据类型选项（仅用于普通模式）
                    dataTypeOptions: [
                        { label: '姓名', value: 'name', sqlTypes: ['varchar', 'char'] },
                        { label: '手机号', value: 'phone', sqlTypes: ['varchar', 'char'] },
                        { label: '邮箱', value: 'email', sqlTypes: ['varchar', 'char'] },
                        { label: '日期时间', value: 'datetime', sqlTypes: ['datetime', 'timestamp'] },
                        { label: '日期', value: 'date', sqlTypes: ['date'] },
                        { label: '整数', value: 'number', sqlTypes: ['int', 'bigint', 'smallint', 'tinyint'] },
                        { label: '小数', value: 'decimal', sqlTypes: ['decimal', 'numeric', 'float', 'double'] },
                        { label: '文本', value: 'text', sqlTypes: ['text', 'longtext', 'mediumtext', 'tinytext'] },
                        { label: '地址', value: 'address', sqlTypes: ['varchar', 'text'] },
                        { label: '公司名', value: 'company', sqlTypes: ['varchar', 'text'] },
                        { label: 'IP地址', value: 'ip', sqlTypes: ['varchar'] },
                        { label: 'URL', value: 'url', sqlTypes: ['varchar', 'text'] }
                    ],
                    // 生成的SQL语句
                    generatedSQL: '',
                    createTableSQL: '',
                    activeTab: 'manual',
                    
                    // AI服务实例
                    aiService: null,
                    // 解析配置
                    parseConfig: {
                        useAI: true,  // 默认使用AI模式
                        loading: false,
                        lastAnalysis: '',
                        loadingText: '', // 添加加载提示文本
                    },
                    loading: false,
                    loadingText: '',
                    showSettings: false,
                    settings: {
                        apiKey: localStorage.getItem('apiKey') || ''
                    },
                    // 历史记录相关
                    historySearch: '',
                    historyRecords: [],
                    dbService: null,
                }
            },
            methods: {
                // 添加新列
                addColumn() {
                    this.tableConfig.columns.push({
                        name: '',
                        type: '',
                        dataType: ''
                    })
                },
                
                // 删除列
                removeColumn(index) {
                    this.tableConfig.columns.splice(index, 1)
                },

                // 更新加载状态
                updateLoadingStatus(status) {
                    this.loadingText = status;
                    if (status === '完成') {
                        setTimeout(() => {
                            this.loading = false;
                        }, 500);
                    }
                },

                // 检查AI配置
                checkAIConfig() {
                    const apiKey = localStorage.getItem('apiKey');
                    if (!apiKey) {
                        this.$message.warning('使用AI功能需要配置API Key，即将跳转到配置中心');
                        setTimeout(() => {
                            this.showSettings = true;
                        }, 1000);
                        return false;
                    }
                    if (!this.aiService) {
                        this.aiService = new AIService(apiKey);
                    }
                    return true;
                },

                // 生成测试数据
                async generateData() {
                    if (this.parseConfig.useAI && !this.checkAIConfig()) return;
                    
                    try {
                        this.loading = true;
                        this.loadingText = '准备生成测试数据...';
                        
                        let sql;
                        if (this.parseConfig.useAI) {
                            // 使用AI生成测试数据
                            sql = await this.aiService.generateTestSQL(
                                this.tableConfig.tableName,
                                this.tableConfig.columns.map(column => {
                                    const placeholderType = this.mapChineseTypeToPlaceholder(column.dataType);
                                    return {
                                        name: column.name,
                                        sql_type: column.type,
                                        data_type: placeholderType,
                                        ...column.aiAnalysis
                                    };
                                }),
                                this.generateConfig.count,
                                this.updateLoadingStatus
                            );
                        } else {
                            // 使用faker.js本地生成测试数据
                            const sqlStatements = [];
                            const fieldNames = this.tableConfig.columns.map(f => f.name);

                            for (let i = 0; i < this.generateConfig.count; i++) {
                                const values = this.tableConfig.columns.map(column => {
                                    return this.generateFakerValue(column.dataType);
                                });

                                const sql = `INSERT INTO ${this.tableConfig.tableName} (${fieldNames.join(', ')}) VALUES (${values.join(', ')});`;
                                sqlStatements.push(sql);

                                if ((i + 1) % 5 === 0) {
                                    this.loadingText = `已生成 ${i + 1} 条数据...`;
                                }
                            }

                            sql = sqlStatements.join('\n');
                        }
                        
                        this.generatedSQL = sql;
                        this.$message.success('测试数据生成成功！');
                        
                        // 生成成功后保存到历史记录
                        await this.saveToHistory();
                    } catch (error) {
                        console.error('生成测试数据失败:', error);
                        this.$message.error('生成测试数据失败：' + error.message);
                    } finally {
                        this.loading = false;
                    }
                },

                // 使用faker.js生成数据
                generateFakerValue(type) {
                    switch (type) {
                        case 'name':
                            return `'${faker.person.fullName()}'`;
                        case 'phone':
                            return `'${faker.phone.number('1##########')}'`;
                        case 'email':
                            return `'${faker.internet.email()}'`;
                        case 'datetime':
                            return `'${faker.date.recent().toISOString().slice(0, 19).replace('T', ' ')}'`;
                        case 'date':
                            return `'${faker.date.recent().toISOString().slice(0, 10)}'`;
                        case 'number':
                            return faker.number.int({ min: 1, max: 1000 });
                        case 'decimal':
                            // 使用 faker.number.int 生成整数部分和小数部分，然后组合
                            const intPart = faker.number.int({ min: 1, max: 1000 });
                            const decimalPart = faker.number.int({ min: 0, max: 99 });
                            return `${intPart}.${decimalPart.toString().padStart(2, '0')}`;
                        case 'text':
                            return `'${faker.lorem.sentence()}'`;
                        case 'address':
                            return `'${faker.location.streetAddress()}'`;
                        case 'company':
                            return `'${faker.company.name()}'`;
                        case 'ip':
                            return `'${faker.internet.ip()}'`;
                        case 'url':
                            return `'${faker.internet.url()}'`;
                        default:
                            return 'NULL';
                    }
                },

                // 将中文类型映射为占位符类型
                mapChineseTypeToPlaceholder(chineseType) {
                    const typeMap = {
                        '姓名': 'name',
                        '手机号': 'phone',
                        '邮箱地址': 'email',
                        '邮箱': 'email',
                        '日期时间': 'datetime',
                        '日期': 'date',
                        '时间': 'datetime',
                        '计数': 'number:1-1000',
                        '数字': 'number:1-1000',
                        '金额': 'number:1-10000',
                        '年龄': 'number:18-80',
                        '性别': 'number:0-2',
                        '文本': 'text',
                        '地址': 'address',
                        '公司名': 'company',
                        'IP地址': 'ip',
                        'URL': 'url',
                        '链接': 'url',
                        '布尔值': 'number:0-1',
                        '密码哈希': 'text'
                    };
                    return typeMap[chineseType] || 'text';
                },

                // 解析CREATE TABLE语句
                async parseCreateTable() {
                    try {
                        this.parseConfig.loading = true;
                        this.parseConfig.loadingText = '正在解析SQL语句...';
                        this.parseConfig.lastAnalysis = '';
                        
                        // 移除注释和多余的空白
                        const sql = this.createTableSQL
                            .replace(/--.*$/gm, '')
                            .replace(/\/\*[\s\S]*?\*\//g, '')
                            .replace(/\s+/g, ' ')
                            .trim();

                        // 提取表名
                        const tableNameMatch = sql.match(/CREATE\s+TABLE\s+(?:`|")?(\w+)(?:`|")?\s*\(/i);
                        if (!tableNameMatch) {
                            throw new Error('无法解析表名，请检查SQL语句格式');
                        }
                        this.tableConfig.tableName = tableNameMatch[1];

                        this.parseConfig.loadingText = '正在分析表结构...';
                        
                        // 提取列定义部分
                        const columnsMatch = sql.match(/\(([\s\S]+)\)/i);
                        if (!columnsMatch) {
                            throw new Error('无法解析列定义，请检查SQL语句格式');
                        }

                        // 分割并处理每一列
                        const columnDefs = columnsMatch[1]
                            .split(',')
                            .map(col => col.trim())
                            .filter(col => {
                                // 过滤掉主键、索引等非列定义
                                const lowerCol = col.toLowerCase();
                                return col && 
                                    !lowerCol.startsWith('primary') && 
                                    !lowerCol.startsWith('key') &&
                                    !lowerCol.startsWith('index') &&
                                    !lowerCol.startsWith('unique') &&
                                    !lowerCol.startsWith('constraint');
                            });

                        // 解析每一列的基本信息
                        this.tableConfig.columns = columnDefs.map(colDef => {
                            // 匹配列名和类型
                            const colMatch = colDef.match(/^(?:`|")?(\w+)(?:`|")?\s+([a-zA-Z]+(?:\([^)]+\))?)/i);
                            if (!colMatch) {
                                console.warn('无法解析列定义:', colDef);
                                return null;
                            }

                            const [, name, type] = colMatch;
                            const column = {
                                name,
                                type: type.toUpperCase(),
                                dataType: '',
                                aiRecommended: false
                            };

                            // 如果是普通模式，根据SQL类型推断数据类型
                            if (!this.parseConfig.useAI) {
                                const sqlType = type.toLowerCase();
                                // 根据SQL类型匹配数据类型选项
                                const matchedOption = this.dataTypeOptions.find(option => 
                                    option.sqlTypes.some(sqlPattern => 
                                        sqlType.includes(sqlPattern.toLowerCase())
                                    )
                                );
                                if (matchedOption) {
                                    column.dataType = matchedOption.value;
                                }
                            }

                            return column;
                        }).filter(Boolean);

                        // 调用AI进行分析
                        if (this.parseConfig.useAI && !this.checkAIConfig()) return;
                        
                        if (this.parseConfig.useAI) {
                            try {
                                this.parseConfig.loadingText = '正在进行AI智能分析，这可能需要一点时间...';
                                const aiAnalysis = await this.aiService.analyzeFieldTypes(this.createTableSQL);
                                
                                // 更新字段的数据类型
                                this.tableConfig.columns = this.tableConfig.columns.map(column => {
                                    const aiFieldInfo = aiAnalysis[column.name];
                                    if (aiFieldInfo) {
                                        column.dataType = aiFieldInfo.type;
                                        column.aiRecommended = true;
                                        column.aiAnalysis = aiFieldInfo;
                                    }
                                    return column;
                                });
                                
                                // 记录解析结果
                                const changedFields = Object.entries(aiAnalysis)
                                    .map(([field, info]) => `${field}: ${info.type}`)
                                    .join(', ');
                                this.parseConfig.lastAnalysis = `AI成功解析字段类型：${changedFields}`;
                                
                                ElementPlus.ElMessage.success('AI分析完成');
                            } catch (error) {
                                console.error('AI分析失败:', error);
                                ElementPlus.ElMessage.error('AI分析失败，请重试');
                                throw error;
                            }
                        } else {
                            ElementPlus.ElMessage.success('解析完成');
                        }

                        if (this.tableConfig.columns.length === 0) {
                            throw new Error('未能解析出任何有效的列定义');
                        }

                    } catch (error) {
                        ElementPlus.ElMessage.error(error.message || 'CREATE TABLE语句解析失败，请检查格式是否正确');
                        console.error('解析错误:', error);
                        this.tableConfig.columns = [];
                    } finally {
                        this.parseConfig.loading = false;
                        this.parseConfig.loadingText = '';
                    }
                },

                // SQL类型映射到faker类型
                mapSqlTypeToFaker(sqlType) {
                    return this.sqlTypeMap[sqlType] || 'text'
                },

                // 新增：复制SQL语句
                copySQL() {
                    navigator.clipboard.writeText(this.generatedSQL).then(() => {
                        ElementPlus.ElMessage.success('复制成功')
                    }).catch(() => {
                        ElementPlus.ElMessage.error('复制失败，请手动复制')
                    })
                },

                // 智能推断数据类型
                inferDataType(name, sqlType, comment = '') {
                    if (!this.parseConfig.useAI) {
                        return this.mapSqlTypeToFaker(sqlType.toLowerCase());
                    }

                    // 转换为小写进行匹配
                    name = name.toLowerCase();
                    comment = comment.toLowerCase();
                    
                    // 根据字段名称匹配
                    for (const [type, keywords] of Object.entries(this.fieldNameMap)) {
                        if (keywords.some(keyword => name.includes(keyword))) {
                            return type;
                        }
                    }

                    // 根据注释匹配
                    if (comment) {
                        if (comment.includes('手机') || comment.includes('电话')) return 'phone';
                        if (comment.includes('邮箱')) return 'email';
                        if (comment.includes('地址')) return 'address';
                        if (comment.includes('公司')) return 'company';
                        if (comment.includes('链接') || comment.includes('url')) return 'url';
                        if (comment.includes('ip')) return 'ip';
                    }

                    // 根据SQL类型匹配
                    sqlType = sqlType.toLowerCase();
                    if (sqlType.includes('char') || sqlType.includes('text')) {
                        // 特殊处理一些常见的文本字段
                        if (name.includes('password') || name.includes('hash')) return 'text';
                        if (name.includes('description') || name.includes('desc')) return 'text';
                        if (name.includes('content')) return 'text';
                        return 'text';
                    }
                    
                    if (sqlType.includes('int') || sqlType.includes('decimal') || sqlType.includes('float')) {
                        return 'number';
                    }
                    
                    if (sqlType.includes('date') || sqlType.includes('time')) {
                        return 'datetime';
                    }

                    return 'text'; // 默认返回文本类型
                },

                // 映射AI返回的类型到前端数据类型
                mapAITypeToDataType(aiType) {
                    // 转换为小写并移除可能的括号内容
                    const type = aiType.toLowerCase().split('(')[0];

                    // 直接匹配的类型
                    const directTypes = ['name', 'phone', 'email', 'address', 'company', 'url', 'ip', 'text'];
                    if (directTypes.includes(type)) {
                        return type;
                    }

                    // 特殊类型映射
                    const typeMap = {
                        'number': 'number',
                        'decimal': 'number',
                        'integer': 'number',
                        'float': 'number',
                        'date': 'date',
                        'datetime': 'datetime',
                        'timestamp': 'datetime',
                        'boolean': 'boolean',
                        'personal name': 'name',
                        'full name': 'name',
                        'phone number': 'phone',
                        'telephone': 'phone',
                        'mobile': 'phone',
                        'email address': 'email',
                        'mail': 'email',
                        'website': 'url',
                        'uri': 'url',
                        'link': 'url',
                        'location': 'address',
                        'addr': 'address',
                        'organization': 'company',
                        'corp': 'company',
                        'enterprise': 'company'
                    };

                    return typeMap[type] || 'text';  // 默认返回text类型
                },

                // 保存配置
                saveSettings() {
                    if (!this.settings.apiKey) {
                        this.$message.error('请输入API Key');
                        return;
                    }
                    localStorage.setItem('apiKey', this.settings.apiKey);
                    this.aiService = new AIService(this.settings.apiKey);
                    this.$message.success('配置保存成功');
                    this.showSettings = false;
                },

                // 初始化AI服务
                initAIService() {
                    const apiKey = localStorage.getItem('apiKey');
                    if (apiKey) {
                        this.aiService = new AIService(apiKey);
                    }
                },

                // 初始化数据库服务
                async initDBService() {
                    this.dbService = new DBService();
                    await this.loadHistoryRecords();
                },

                // 加载历史记录
                async loadHistoryRecords() {
                    try {
                        this.historyRecords = await this.dbService.getAllHistory();
                    } catch (error) {
                        console.error('加载历史记录失败:', error);
                        this.$message.error('加载历史记录失败');
                    }
                },

                // 搜索历史记录
                async searchHistory() {
                    try {
                        if (this.historySearch.trim()) {
                            this.historyRecords = await this.dbService.searchHistory(this.historySearch.trim());
                        } else {
                            await this.loadHistoryRecords();
                        }
                    } catch (error) {
                        console.error('搜索历史记录失败:', error);
                        this.$message.error('搜索历史记录失败');
                    }
                },

                // 保存当前配置到历史记录
                async saveToHistory() {
                    try {
                        // 创建一个新的对象，只包含需要的数据
                        const record = {
                            tableName: this.tableConfig.tableName,
                            // 深拷贝并清理列数据
                            columns: this.tableConfig.columns.map(column => ({
                                name: column.name,
                                type: column.type,
                                dataType: column.dataType,
                                aiRecommended: column.aiRecommended || false
                            })),
                            createTableSQL: this.createTableSQL,
                            useAI: this.parseConfig.useAI,
                            generatedSQL: this.generatedSQL,
                            generateConfig: {
                                count: this.generateConfig.count
                            },
                            timestamp: new Date().getTime()
                        };
                        
                        await this.dbService.saveHistory(record);
                        this.$message.success('已保存到历史记录');
                        await this.loadHistoryRecords();
                    } catch (error) {
                        console.error('保存历史记录失败:', error);
                        this.$message.error('保存历史记录失败');
                    }
                },

                // 加载历史记录
                async loadHistory(record) {
                    try {
                        this.tableConfig.tableName = record.tableName;
                        this.tableConfig.columns = record.columns;
                        this.createTableSQL = record.createTableSQL;
                        this.parseConfig.useAI = record.useAI;
                        this.generatedSQL = record.generatedSQL;
                        this.generateConfig = {
                            count: record.generateConfig.count
                        };
                        
                        // 切换到手动配置标签页
                        this.activeTab = 'manual';
                        this.$message.success('历史记录加载成功');
                    } catch (error) {
                        console.error('加载历史记录失败:', error);
                        this.$message.error('加载历史记录失败');
                    }
                },

                // 删除历史记录
                async deleteHistory(id) {
                    try {
                        await this.dbService.deleteHistory(id);
                        this.$message.success('删除成功');
                        await this.loadHistoryRecords();
                    } catch (error) {
                        console.error('删除历史记录失败:', error);
                        this.$message.error('删除历史记录失败');
                    }
                },

                // 清空历史记录
                async clearHistory() {
                    try {
                        await this.$confirm('确定要清空所有历史记录吗？', '警告', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        });
                        
                        await this.dbService.clearHistory();
                        this.$message.success('历史记录已清空');
                        this.historyRecords = [];
                    } catch (error) {
                        if (error !== 'cancel') {
                            console.error('清空历史记录失败:', error);
                            this.$message.error('清空历史记录失败');
                        }
                    }
                },

                // 取消当前操作
                cancelOperation() {
                    if (this.aiService) {
                        this.aiService.cancelCurrentCall();
                    }
                    this.loading = false;
                    this.loadingText = '';
                    this.$message.info('操作已取消');
                },
            },
            mounted() {
                this.initAIService();
                this.initDBService();
            },
            setup() {
                return {
                    Setting
                }
            }
        }

        // 等待所有资源加载完成后再初始化应用
        window.onload = function() {
            const vueApp = createApp(app)
            vueApp.use(ElementPlus)
            for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
                vueApp.component(key, component)
            }
            vueApp.mount('#app')
        }
    </script>
</body>
</html> 